<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Income extends Model
{

    // 表名
    protected $name = 'kuyou_income';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,pay_money,preparation_id,examine_id,pay_status,examine_status,print_num,remark,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,pay_money,preparation_id,examine_id,pay_status,examine_status,print_num,remark,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,pay_money,preparation_id,examine_id,pay_status,examine_status,print_num,remark,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time,arrears,accounts_id")->find();
        if($detail){
            $detail['customers'] = (new Customers())->where(['id'=>$detail['customers_id']])->value('customer_name');
            $detail['accounts'] = (new Accounts())->where(['id'=>$detail['accounts_id']])->value('account_name');
            $account = Db::name('kuyou_income_info')->where(['purchase_id'=>$detail['id']])
                ->field("purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,customers_id,income_type_id,money,remark")->select();
            foreach ($account as $account_k=>$account_v){
                $account[$account_k]['income_type'] = (new IncomeType())->where(['id'=>$account_v['income_type_id']])->value('name');
            }
            $detail['info_list'] = $account;
        }
        if(!empty($detail)){
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'customers_id|客户'=>'require|number',
                'pay_money|收款金额'=>'require|money',
                'arrears|本次欠款'=>'require|money',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],24);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');
                    $info_list = (array)json_decode($detail['info_list'], true);

                    if(!empty($detail['customers_id'])){
                        $customers = Db::name('kuyou_customers')->where(['id'=>$detail['customers_id']])->find();
                        if(empty($customers)){
                            return ['status'=>500,'msg'=>'客户信息错误'];
                        }
                    }

                    $money = 0;
                    foreach ($info_list as $k=>$v){
                        if($v['money']!==''){
                            if($v['money']<=0){
                                return ['status'=>500,'msg'=>'收入金额不能小于0'];
                            }else if(empty($v['income_type_id'])){
                                return ['status'=>500,'msg'=>'请选择收入类别'];
                            }else{
                                $money += (float)$v['money'];
                                $income_type = Db::name('kuyou_income_type')->where(['id'=>$v['income_type_id']])->find();
                                if(empty($income_type)){
                                    return ['status'=>500,'msg'=>'收入类别查询错误'];
                                }
                                $data[] = [
                                    'purchase_code'    => $detail['purchase_code'],
                                    'purchase_time'    => strtotime($detail['purchase_time']),
                                    'business_type'    => '1',
                                    'customers_id'     => isset($customers)?$customers['id']:null,
                                    'income_type_id'   => $income_type['id'],
                                    'money'            => (float)$v['money'],
                                    'remark'           => $v['remark']!==''?$v['remark']:'',
                                    'createtime'       => time(),
                                    'updatetime'       => time(),
                                ];
                            }
                        }
                    }

                    if($money<=0){
                        return ['status'=>500,'msg'=>'收入金额不能小于0'];
                    }else if($money>0 && empty($detail['accounts_id'])){
                        return ['status'=>500,'msg'=>'请选择结算账户'];
                    }else if($detail['pay_money']>0 && $detail['pay_money']>$money){
                        return ['status'=>500,'msg'=>'收款金额不能大于收入金额'];
                    }else{
                        $accounts = Db::name('kuyou_accounts')->where(['id'=>$detail['accounts_id']])->find();
                        if(empty($accounts)){
                            return ['status'=>500,'msg'=>'结算账户信息错误'];
                        }
                    }

                    $pay_status = 0;
                    if($detail['pay_money']>0){
                        $pay_status = $money==$detail['pay_money']?1:2;
                    }
                    $detail['cost_id'] = isset($detail['cost_id'])?$detail['cost_id']:'';
                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     =>  '1',
                        'customers_id'      =>  isset($customers)?$customers['id']:null,
                        'accounts_id'       =>  isset($accounts)?$accounts['id']:null,
                        'cost_id'           =>  $detail['cost_id']!==''?$detail['cost_id']:null,
                        'money'             =>  $money,
                        'pay_money'         =>  $detail['pay_money']!==''?(float)$detail['pay_money']:null,
                        'arrears'           =>  $detail['arrears']!==''?(float)$detail['arrears']:null,
                        'remark'            =>  $detail['remark'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'pay_status'        =>  $pay_status,
                        'createtime'        =>  time(),
                        'updatetime'        =>  time(),
                    ];

                    $model = new Income();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        foreach ($data as $data_k=>$data_v){
                            $data[$data_k]['purchase_id'] = $result;
                        }
                        Db::name('kuyou_income_info')->insertAll($data);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'customers_id|客户'=>'require|number',
                'pay_money|收款金额'=>'require|money',
                'arrears|本次欠款'=>'require|money',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],24);//验证编号是否合法
                if($status){
                    $model = new Income();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $old_purchase_code = $detail['old_purchase_code'];
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $info_list = (array)json_decode($detail['info_list'], true);

                    if(!empty($detail['customers_id'])){
                        $customers = Db::name('kuyou_customers')->where(['id'=>$detail['customers_id']])->find();
                        if(empty($customers)){
                            return ['status'=>500,'msg'=>'客户信息错误'];
                        }
                    }

                    $money = 0;
                    foreach ($info_list as $k=>$v){
                        if($v['money']!==''){
                            if($v['money']<=0){
                                return ['status'=>500,'msg'=>'收入金额不能小于0'];
                            }else if(empty($v['income_type_id'])){
                                return ['status'=>500,'msg'=>'请选择收入类别'];
                            }else{
                                $money += (float)$v['money'];
                                $income_type = Db::name('kuyou_income_type')->where(['id'=>$v['income_type_id']])->find();
                                if(empty($income_type)){
                                    return ['status'=>500,'msg'=>'收入类别查询错误'];
                                }
                                $data[] = [
                                    'purchase_code'    => $detail['purchase_code'],
                                    'purchase_time'    => strtotime($detail['purchase_time']),
                                    'business_type'    => '1',
                                    'customers_id'     => isset($customers)?$customers['id']:null,
                                    'income_type_id'   => $income_type['id'],
                                    'money'            => (float)$v['money'],
                                    'remark'           => $v['remark']!==''?$v['remark']:'',
                                    'createtime'       => time(),
                                    'updatetime'       => time(),
                                ];
                            }
                        }
                    }

                    if($money<=0){
                        return ['status'=>500,'msg'=>'收入金额不能小于0'];
                    }else if($money>0 && empty($detail['accounts_id'])){
                        return ['status'=>500,'msg'=>'请选择结算账户'];
                    }else if($detail['pay_money']>0 && $detail['pay_money']>$money){
                        return ['status'=>500,'msg'=>'收款金额不能大于收入金额'];
                    }else{
                        $accounts = Db::name('kuyou_accounts')->where(['id'=>$detail['accounts_id']])->find();
                        if(empty($accounts)){
                            return ['status'=>500,'msg'=>'结算账户信息错误'];
                        }
                    }

                    $pay_status = 0;
                    if($detail['pay_money']>0){
                        $pay_status = $money==$detail['pay_money']?1:2;
                    }
                    $detail['cost_id'] = isset($detail['cost_id'])?$detail['cost_id']:'';
                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     =>  '1',
                        'customers_id'      =>  isset($customers)?$customers['id']:null,
                        'accounts_id'       =>  isset($accounts)?$accounts['id']:null,
                        'cost_id'           =>  $detail['cost_id']!==''?$detail['cost_id']:null,
                        'money'             =>  $money,
                        'pay_money'         =>  $detail['pay_money']!==''?(float)$detail['pay_money']:null,
                        'arrears'           =>  $detail['arrears']!==''?(float)$detail['arrears']:null,
                        'remark'            =>  $detail['remark'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'pay_status'        =>  $pay_status,
                        'updatetime'        =>  time(),
                    ];

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);

                            Db::name('kuyou_income_info')->where(['purchase_id'=>$row['id']])->delete();
                            foreach ($data as $data_k=>$data_v){
                                $data[$data_k]['purchase_id'] = $row['id'];
                            }
                            Db::name('kuyou_income_info')->insertAll($data);
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Income();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            $del_id = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }else{
                    $del_id[] = $list_v['id'];
                }
            }
            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                }
                Db::name('kuyou_income_info')->where(['purchase_id'=>['in',$del_id]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Income();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }

        $income_order = [];//采购销售费用
        $account_list = [];//账户
        $account_log  = [];//账户记录
        $accounts_receivable = [];//应收账款明细表
        foreach ($list as $list_k=>$list_v){
            //关联采购销售费用
            if(!empty($list_v['cost_id'])){
                $cost = Db::name('kuyou_cost')->where(['id'=>$list_v['cost_id']])->find();
                if(empty($cost)){
                    return ['status'=>500,'msg'=>'编号'.$list_v['purchase_code'].'审核失败，关联的采购销售费用数据错误'];
                }
                $status = true;
                foreach ($income_order as $income_order_k=>$income_order_v){
                    if($income_order_v['id']==$cost['id']){
                        $status = false;
                        $income_order[$income_order_k]['pay_money'] -= $list_v['pay_money'];
                    }
                }
                if($status){
                    $income_order[] = [
                        'id'        => $list_v['cost_id'],
                        'pay_money' => $cost['pay_money'] - $list_v['pay_money'],
                    ];
                }
            }
            //账户信息
            $account = Db::name('kuyou_accounts')->where(['id'=>$list_v['accounts_id']])->find();
            $status = true;
            foreach ($account_list as $account_list_k=>$account_list_v){
                if($account_list_v['id']==$account['id']){
                    $status = false;
                    $account_list[$account_list_k]['balance'] += $list_v['pay_money'];
                }
            }
            if($status){
                $account_list[] = [
                    'id'        => $account['id'],
                    'balance'   => $account['balance'] + $list_v['pay_money'],
                ];
            }
            //账户记录
            $account_log[] = [
                'account_coding'    => $account['account_coding'],
                'account_name'      => $account['account_name'],
                'balance'           => $account['balance']+$list_v['pay_money'],
                'income'            => $list_v['pay_money'],
                'pay_time'          => time(),
                'bill_code'         => $list_v['purchase_code'],
                'business_type'     => '9',
                'customers_id'      => $list_v['customers_id'],
                'remark'            => $list_v['remark'],
                'createtime'        => time(),
                'updatetime'        => time(),
            ];

            //应收账款明细表
            if($list_v['pay_money']<$list_v['money']){
                $accounts_receivable[] = [
                    'customers_id'      => $list_v['customers_id'],
                    'purchase_time'     => $list_v['purchase_time'],
                    'purchase_code'     => $list_v['purchase_code'],
                    'business_type'     => '8',
                    'receivable'        => $list_v['arrears'],
                    'sale_money'        => $list_v['money'],
                    'receivable_money'  => $list_v['money'],
                    'real_money'        => $list_v['pay_money'],
                    'remark'            => $list_v['remark'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
            }
        }
        $result = false;
        Db::startTrans();
        try {
            if(!empty($accounts_receivable)){
                Db::name('kuyou_accounts_receivable')->insertAll($accounts_receivable);
            }
            if(!empty($account_log)){
                Db::name('kuyou_accounts_log')->insertAll($account_log);
            }
            if(!empty($account_list)){
                (new Accounts())->saveAll($account_list);
            }
            if(!empty($income_order)){
                (new Cost())->saveAll($income_order);
            }
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])
                ->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }

        $model = new Income();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }

        $income_order = [];//采购销售费用
        $account_list = [];//账户
        $purchase_code = [];//单据编号
        foreach ($list as $list_k=>$list_v){
            $purchase_code[] = $list_v['purchase_code'];
            //关联采购销售费用
            if(!empty($list_v['cost_id'])){
                $cost = Db::name('kuyou_cost')->where(['id'=>$list_v['cost_id']])->find();
                if(empty($cost)){
                    return ['status'=>500,'msg'=>'编号'.$list_v['purchase_code'].'审核失败，关联的采购销售费用数据错误'];
                }
                $status = true;
                foreach ($income_order as $income_order_k=>$income_order_v){
                    if($income_order_v['id']==$cost['id']){
                        $status = false;
                        $income_order[$income_order_k]['pay_money'] += $list_v['pay_money'];
                    }
                }
                if($status){
                    $income_order[] = [
                        'id'        => $list_v['cost_id'],
                        'pay_money' => $cost['pay_money'] + $list_v['pay_money'],
                    ];
                }
            }
            //账户信息
            $account = Db::name('kuyou_accounts')->where(['id'=>$list_v['accounts_id']])->find();
            $status = true;
            foreach ($account_list as $account_list_k=>$account_list_v){
                if($account_list_v['id']==$account['id']){
                    $status = false;
                    $account_list[$account_list_k]['balance'] -= $list_v['pay_money'];
                }
            }
            if($status){
                $account_list[] = [
                    'id'        => $account['id'],
                    'balance'   => $account['balance'] - $list_v['pay_money'],
                ];
            }
        }
        Db::startTrans();
        try {
            Db::name('kuyou_accounts_receivable')->where(['business_type'=>'8','purchase_code'=>['in',$purchase_code]])->delete();
            Db::name('kuyou_accounts_log')->where(['business_type'=>'9','bill_code'=>['in',$purchase_code]])->delete();
            if(!empty($account_list)){
                (new Accounts())->saveAll($account_list);
            }
            if(!empty($income_order)){
                (new Cost())->saveAll($income_order);
            }
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])
                ->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

}
